package com.frank.oj.service.file.impl;

import com.alibaba.excel.EasyExcel;
import com.frank.oj.model.vo.ExcelUserVO;
import com.frank.oj.service.file.UserFileService;
import com.frank.oj.utils.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author frank
 * @Date 2024/3/28
 */
@Service
public class UserFileServiceImpl implements UserFileService {
    @Resource
    private RedisUtils redisUtils;
    @Override
    public void generateUserExcel(String key, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode(key, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Content-Type","application/xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelUserVO.class).sheet("自动生成的用户相关信息").doWrite(getGenerateUsers(key));
    }

    private List<ExcelUserVO> getGenerateUsers(String key) {

        List<ExcelUserVO> excelUsers = new LinkedList<>();
        Map<Object, Object> newUserInfo = redisUtils.hmget(key);

        for (Object hashKey : newUserInfo.keySet()) {
            String username=(String) hashKey;
            String password=(String) newUserInfo.get(hashKey);

            excelUsers.add(new ExcelUserVO().setUsername(username).setPassword(password));
        }
        return excelUsers;
    }
}
